package oop.controller.action.test;

import java.sql.SQLException;

import oop.controller.action.DefaultAction;
import oop.data.Section;
import oop.data.Test;
import oop.db.dao.SectionDAO;
import oop.db.dao.SectionQuestionAnswerDAO;
import oop.db.dao.SectionQuestionDAO;
import oop.db.dao.TestVersionDAO;

public class DeleteQuestionAction extends DefaultAction {

	public DeleteQuestionAction() {
	}

	@Override
	public void performImpl() throws Exception {
		title("Gỡ bỏ câu hỏi khỏi đề thi");
		try {
			long sectionId = getParams().getLong("tdq_sectid");
			Section section = SectionDAO.fetchById(sectionId).get(0);
			Test test = section.getTest();

			try {
				TestVersionDAO.dropByTest(test.getId());
			} catch (SQLException e) {
				if (e.getErrorCode() == 1451) {
					error("Không thể sửa đề thi đang sử dụng");
					return;
				} else {
					throw e;
				}
			}

			long questionId = Long.parseLong(request
					.getParameter("tdq_question"));
			SectionQuestionAnswerDAO.removeAnswers(sectionId, questionId);
			SectionQuestionDAO.removeQuestion(sectionId, questionId);
			setNextAction("test.view&tv_id=" + test.getId());
		} catch (NumberFormatException ex) {
			error("ID không hợp lệ");
		}
	}

}
